package com.hs.mod_archive.fragment

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.lifecycleScope
import com.hs.framework.base.BaseDataBindFragment
import com.hs.framework.toast.TipsToast
import com.hs.framework.utils.Speech
import com.hs.framework.utils.ValidateUtils
import com.hs.mod_archive.R
import com.hs.mod_archive.databinding.DialogAddCabinetBinding
import com.hs.mod_archive.databinding.FragmentDevCabinetConfigBinding
import com.hs.mod_archive.helper.DevCabinetHelper
import com.hs.mod_archive.helper.ListViewHelper
import com.hs.mod_archive.helper.ListViewHelper.Companion.perPageCount
import com.hs.mod_archive.view.DialogUtil
import com.hs.mod_archive.view.MyDialog
import com.hs.room.model.archive.ArchiveLevel
import com.hs.room.model.archive.ArchiveType
import com.hs.room.model.archive.DevCabinet
import com.hs.room.repository.service.IArchiveDictRepository
import com.hs.room.repository.service.IDevRepository
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class FragmentDevCabinetConfig : BaseDataBindFragment<FragmentDevCabinetConfigBinding>() {
    private lateinit var level: List<ArchiveLevel>
    private lateinit var type: List<ArchiveType>
    private var datas: List<DevCabinet>? = null

    @Inject
    lateinit var service: IDevRepository

    @Inject
    lateinit var dictService: IArchiveDictRepository

    lateinit var names: List<String>
    lateinit var helper: DevCabinetHelper
    var dialogEdit: MyDialog? = null
    var dialogBinding: DialogAddCabinetBinding? = null
    override fun initView(view: View, savedInstanceState: Bundle?) {
        mBinding!!.btAdd.setOnClickListener { showDialog() }
        helper =
            DevCabinetHelper(
                mBinding!!.footPageListView, object : ListViewHelper.OnItemClickListener {
                    override fun onItemClickEdit(p: Int) {
                    }

                    override fun onItemClickDelete(p: Int) {
                        del(datas!!.get(p))
                    }
                },
                object : ListViewHelper.FootSearchCallback {
                    override fun onActionSearch(i: Int) {
                        goPage(i)
                    }
                })
    }

    private fun goPage(i: Int) {
        lifecycleScope.launch {
            service.getDevCabinet(i, perPageCount).collect {
                helper.setListDataAndRefresh(it)
                datas = it
            }
        }
    }

    private fun del(d: DevCabinet) {
        lifecycleScope.launch {
            service.delete(d)
            TipsToast.showTips("删除成功")
        }
    }


    override fun initData() {
        super.initData()
        lifecycleScope.launch {
            val count: Int = service.countDevCabinet()
            service.getDevCabinetName().collect {
                names = it
            }
            helper.setFootValue(count, 0)

        }
        lifecycleScope.launch {
            dictService.getType(0, 100).collect {
                var m = listOf(ArchiveType(0, 0, "忽略", "", 0, "0", true))
                m = m.toMutableList()
                m.addAll(it)
                type = m
            }
        }
        lifecycleScope.launch {
            dictService.getLevel(0, 100).collect {
                var mlist = listOf(ArchiveLevel(0, 0, "忽略", "", 0, "0", true))
                mlist = mlist.toMutableList()
                mlist.addAll(it)
                level = mlist
            }
        }
        goPage(0)
    }

    private fun showDialog() {
        if (null == dialogBinding) {
            dialogBinding = DialogAddCabinetBinding.inflate(layoutInflater)
        }
        // 设置适配器
        val adapter = ArrayAdapter(requireActivity(), android.R.layout.simple_spinner_item, type)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        dialogBinding!!.type.adapter = adapter

        // 设置适配器
        val adapter1 = ArrayAdapter(requireActivity(), android.R.layout.simple_spinner_item, level)
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        dialogBinding!!.level.adapter = adapter1


        // 设置选择监听器
        dialogBinding!!.btSubmit.setOnClickListener { _ ->
            if (!ValidateUtils.notNull(
                    dialogBinding!!.name,
                    getString(R.string.name)
                ) || !ValidateUtils.notNull(
                    dialogBinding!!.bID,
                    getString(R.string.lockBoard)
                ) || !ValidateUtils.notNull(
                    dialogBinding!!.bNo,
                    getString(R.string.lockNo)
//                ) || !ValidateUtils.notNull(
//                    dialogBinding!!.lID,
//                    getString(R.string.lampBoard)
//                ) || !ValidateUtils.notNull(
//                    dialogBinding!!.lNo,
//                    getString(R.string.lampNo)
                )
            ) {
                return@setOnClickListener
            }
            val name: String = dialogBinding!!.name.text.toString().trim()
            if (names.contains(name)) {
                Speech.speak(getString(R.string.nameExist))
                return@setOnClickListener
            }
            val bid: String = dialogBinding!!.bID.text.toString().trim()
            val bno: String = dialogBinding!!.bNo.text.toString().trim()
//            val lid: String = dialogBinding!!.lID.text.toString().trim()
//            val lno: String = dialogBinding!!.lNo.text.toString().trim()
            val l: String = dialogBinding!!.level.selectedItem.toString()
            val t: String = dialogBinding!!.type.selectedItem.toString()
            var levelId = 0L
            level.forEach {
                if (l.equals(it.alName)) {
                    levelId = it.localId
                }
            }
            var typeId = 0L
            type.forEach {
                if (t.equals(it.atName)) {
                    typeId = it.localId
                }
            }
            var d = DevCabinet(
                0,
                0,
                name,
                bid.toInt(),
                bno.toInt(),
                0, 0,
//                lid.toInt(),
//                lno.toInt(),
                dialogBinding!!.runningIndicator.isChecked,
                if (dialogBinding!!.lamp.checkedRadioButtonId == R.id.rb_b) {
                    2
                } else if (dialogBinding!!.lamp.checkedRadioButtonId == R.id.rb_g) {
                    1
                } else {
                    0
                },
                0,
                typeId, levelId, dialogBinding!!.remark.text.toString()
            )
            submitName(
                d
            )
        }
        val root: ConstraintLayout = dialogBinding!!.getRoot()
        val parent = root.parent
        if (null != parent) {
            val viewGroup = parent as ViewGroup
            viewGroup.removeView(root)
            dialogBinding!!.name.setText("")
            dialogBinding!!.bID.setText("")
            dialogBinding!!.bNo.setText("")
//            dialogBinding!!.lID.setText("")
//            dialogBinding!!.lNo.setText("")
        }
        dialogBinding!!.btClose.setOnClickListener { _ -> dismissDialog() }
        dialogBinding!!.btCancel.setOnClickListener { _ -> dismissDialog() }
        //-------------------------
        val w = resources.getDimensionPixelSize(R.dimen.dp_582)
        val h = resources.getDimensionPixelSize(R.dimen.dp_482)
        dialogEdit = DialogUtil.buildSpecialView(activity, root, w, h, false, false)
    }

    fun dismissDialog() {
        dialogEdit?.dismiss()
        dialogEdit = null
        dialogBinding = null
    }

    private fun submitName(
        d: DevCabinet
    ) {
        insert(d)
        dismissDialog()
    }

    fun update(src: DevCabinet) {
        lifecycleScope.launch {
            service.update(src)
        }
    }

    fun insert(src: DevCabinet) {
        lifecycleScope.launch {
            service.insert(src)
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        helper.onDestroyView()
    }
}
